package com.example.musicplayer;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.json.JSONArray;
import org.json.JSONObject;

import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class SearchSong {
	private static final int DOWNLOAD_COMPLETE = 1455;
	private static final int READ_FILE = 4646;
	private static final int DOWNLOAD_FAILED = 14684;
	protected static final int DOWNLOAD_SONG_COMPLETE = 26512;
	protected static final int DOWNLOADING_SONG = 46864;
	protected static final int DOWNLOAD_SONG_FAILED = 85245;
	final String BASE_URL = "http://tingapi.ting.baidu.com/v1/restserver/ting?form=webapp_music&method=baidu.ting.search.catalogSug&format=json&callback=&query=";
	final String MUSIC_URL = "http://ting.baidu.com/data/music/links?songIds=";
	final String lrcDrectory = "/MusicPlayer/lrc/";
	final String songDrectory = "/MusicPlayer/songs/";
	final String appDrectory = "/MusicPlayer/";
	String musicFormat = "";
	String lrcLink = "";
	String albumLink = "";
	String songLink = "";
	String songId = "";
	String PATH = "";
	String xCode = "";
	String author = "";
	String src = "";
	String musicNameString = "";
	List<Map<String, String>> resultList;
	boolean downloadComplet = false;

	public SearchSong(String keyWords) throws UnsupportedEncodingException,
			Exception {
		// TODO Auto-generated constructor stub
		getSongId(BASE_URL + URLEncoder.encode(keyWords, "UTF-8"));
	}

	public SearchSong() {
		// TODO Auto-generated constructor stub
	}

	public List<Map<String, String>> getList() {
		return resultList;
	}

	public void getLinks(String songId) {
		// TODO Auto-generated method stub
		try {
			if (songId == "" || songId == null) {
				return;
			}
			JSONObject jsonObject = readJason(MUSIC_URL + songId);
			if (jsonObject.get("data").toString() == ""
					|| jsonObject.get("data").toString() == null) {
				return;
			}
			xCode = (String) jsonObject.getJSONObject("data").get("xcode");
			if (jsonObject.getJSONObject("data").get("songList") != ""
					&& jsonObject.getJSONObject("data").get("songList") != null) {
				JSONArray jsonArray = jsonObject.getJSONObject("data")
						.getJSONArray("songList");
				lrcLink = jsonArray.getJSONObject(0).get("lrcLink").toString();
				songLink = jsonArray.getJSONObject(0).get("songLink")
						.toString();
				musicFormat = jsonArray.getJSONObject(0).get("format")
						.toString();
			} else {
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public String getSongLink() {
		return songLink;
	}

	public String getLrcLink() {
		return lrcLink;
	}

	public List<Map<String, String>> getSongId(String path) throws Exception {
		resultList = new ArrayList<Map<String, String>>();
		try {
			JSONObject jsonObject = readJason(path);
			JSONArray jsonArray = jsonObject.getJSONArray("song");
			for (int i = 0; i < jsonArray.length(); i++) {
				Map<String, String> map = new HashMap<String, String>();
				map.put("Author",
						URLDecoder.decode(
								jsonArray.getJSONObject(i).get("artistname")
										.toString(), "utf-8"));
				map.put("songid", jsonArray.getJSONObject(i).get("songid")
						.toString());
				map.put("MusicName",
						URLDecoder.decode(
								jsonArray.getJSONObject(i).get("songname")
										.toString(), "utf-8"));
				resultList.add(map);
			}
			return resultList;
		} catch (Exception e) {
			Log.i("expactation", e.toString());
		}
		return resultList;

	}

	public JSONObject readJason(String urlString) throws Exception {
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		byte[] data = new byte[1024];
		URL url = new URL(urlString);
		HttpURLConnection hUrlConnection = (HttpURLConnection) url
				.openConnection();
		if (hUrlConnection.getResponseCode() == 200) {
			InputStream inputStream = hUrlConnection.getInputStream();
			Log.i("code", hUrlConnection.getResponseCode() + "");
			int len = 0;
			while ((len = inputStream.read(data)) != -1) {
				byteArrayOutputStream.write(data, 0, len);
			}
			inputStream.close();
			byte[] bytes = byteArrayOutputStream.toByteArray();
			JSONObject jsonObject = new JSONObject(new String(bytes));
			return jsonObject;
		}
		return null;

	}

	public void downLoadLrc(String songName) throws IOException {
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		byte[] data = new byte[1024];
		Log.i("link", lrcLink + "?xcode=" + xCode);
		if (lrcLink == "" || lrcLink == null) {
			return;
		}
		URL url = new URL("http://ting.baidu.com" + lrcLink + "?xcode=" + xCode);
		HttpURLConnection hUrlConnection = (HttpURLConnection) url
				.openConnection();
		hUrlConnection.setRequestMethod("GET");
		if (hUrlConnection.getResponseCode() == 200) {
			InputStream inputStream = hUrlConnection.getInputStream();
			Log.i("code", hUrlConnection.getResponseCode() + "");
			int len = 0;
			while ((len = inputStream.read(data)) != -1) {
				byteArrayOutputStream.write(data, 0, len);
			}
			inputStream.close();
			sdcardsevice sdcardsevice = new sdcardsevice();
			sdcardsevice.saveContentToSd(lrcDrectory, songName + ".lrc",
					byteArrayOutputStream.toString());
			byteArrayOutputStream.close();
			Log.i("log", "downComplete");
		}
	}

	public void downLoadMusic(String songName, Handler handler)
			throws Exception {
		byte[] data = new byte[1024];
		if (songLink == "" || songLink == null) {
			return;
		}
		URL url = new URL(songLink + "?xcode=" + xCode);
		HttpURLConnection hUrlConnection = (HttpURLConnection) url
				.openConnection();
		if (hUrlConnection.getResponseCode() == 200) {
			InputStream inputStream = hUrlConnection.getInputStream();
			FileOutputStream fileOutputStream = null;
			if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) {
				File file = new File(Environment.getExternalStorageDirectory()
						+ songDrectory, songName + "." + musicFormat);
				if (!file.exists()) {
					file.createNewFile();
				}
				fileOutputStream = new FileOutputStream(file);
			} else {
				handler.sendEmptyMessage(DOWNLOAD_SONG_FAILED);
				return;
			}
			int total = hUrlConnection.getContentLength();
			int current = 0;
			int len = 0;
			try {
				while ((len = inputStream.read(data)) != -1) {
					fileOutputStream.write(data, 0, len);
					current += len;
					Message msg = new Message();
					msg.what = DOWNLOADING_SONG;
					msg.arg1 = current;
					msg.arg2 = total;
					handler.sendMessage(msg);
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				handler.sendEmptyMessage(DOWNLOAD_SONG_FAILED);
				e.printStackTrace();
			}
			inputStream.close();
			handler.sendEmptyMessage(DOWNLOAD_SONG_COMPLETE);
			Log.i("log", "downComplete");
		}
	}
}
